'use strict';

get('https://back.putar.top/product').then(res => vm.products = res.data);

let vm = new Vue({
    el: '#shoppingCart',
    data: {
        products: [],
        checkedId: [],
    },
    computed: {
        total: function () {
            let res = []
            let total;
            if (this.checkedId.length > 0) {
                this.products.forEach(item => {
                    if (this.checkedId.indexOf(item.id) !== -1) {
                        res.push(item.price*item.stock)
                    }
                })

                total = res.reduce((x, y) => x + y).toFixed(2);
            }

            return total || 0;
        },
        all: {
            get () {
                return this.checkedId.length > 0
            },
            set (newValue) {
                if(newValue) {
                    this.checkedId = this.products.map(item => item.id);
                } else {
                    this.checkedId = []
                }
            }
        }
    },
    methods: {
        removeRange: function () {
            if (this.checkedId.length > 0) {
                this.products = this.products.filter(item => {
                    let i = this.checkedId.indexOf(item.id);
                    if (i !== -1) {
                        this.checkedId[i] = false;
                        this.checkedId.splice(i, 1);
                    }
                    return i == -1;
                })
            } else {
                alert('请选择要结算的商品')
            }
        },
        remove: function (index) {
            let  i = this.checkedId.indexOf(this.products[index].id);
            if (confirm(`确实要删除序号为${index+1}的项目吗?`)) {
                if (i !== -1) {
                    this.checkedId.splice(i, 1);
                }
                this.products.splice(index, 1);
            }
        }
    }
})

